<template>
  <div class="avue-tags">
    <!-- 面包屑盒子 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item
        v-for="(crumb, index) in breadcrumbs"
        :key="index"
        @click="handleBreadcrumbClick(crumb)"
        class="breadcrumb-item"
        :class="{ 'breadcrumb-item_active': index === breadcrumbs.length - 1 }"
      >
        {{ getLabel(crumb.label) }}
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';

export default {
  name: 'Breadcrumbs',
  data() {
    return {};
  },
  computed: {
    ...mapGetters(['setting', 'menu']),
    // 计算面包屑列表
    breadcrumbs() {
      let breadcrumbs = [];
      // 从当前激活路由中获取层级路径
      const matchedRoutes = this.$route.matched;
      const [_, ...crumbs] = matchedRoutes;

      crumbs.forEach(route => {
        breadcrumbs.push({
          path: this.$route.path,
          label: route.name,
        });
      });
      const parentMenuId = this.$route.meta.parentMenuId;
      if (parentMenuId) {
        const menuAll = this.$store.getters.menuAll;
        const menuItem = this.findNode(menuAll, parentMenuId);
        breadcrumbs.unshift({
          path: menuItem?.path,
          label: menuItem?.name,
        });
      }
      return breadcrumbs;
    },
  },
  methods: {
    // 处理面包屑点击事件，导航到相应路径
    handleBreadcrumbClick(crumb) {
      this.$router.push(crumb.path);
    },
    // 获取逗号前面的 label 部分
    getLabel(label) {
      try {
        return label.split(',')[0];
      } catch (err) {
        return label;
      }
    },
  },
};
</script>
<style>
.avue-tags {
  height: 35px;
}
</style>
